require.config({
	baseUrl: "/res/js",
	paths: {
        js: './',
        jquery: './jquery-1.9.1.min',
        placeholder: "./jquery.placeholder.min",
        qrcode: "./jquery.qrcode-0.11.0.min",
        media: "./html5media-1.1.8/html5media.min",
        jwerty: './jwerty',
        bootstrap: './bootstrap-3.3.5/bootstrap.min'
        
    }
});

define(["jquery"],function() {
	g_contextPath = "";//document.getElementById("domain").href;
	// 插件配置
	var plugins = {
		validator: {
			js:[
			    "validator-0.7.3/jquery.validator",
			    "validator-0.7.3/local/zh_CN"
			   ],
			css:["/res/js/validator-0.7.3/jquery.validator.css"]
			
		},
		common: {
			js:[],
			css:["/res/css/my-com.css"]
		}
	};

	window.loadjs = function(names, callback) {
		var LOADING = "loading",LOADED = "loaded";
		var pluginNum = names.length;
		var len = pluginNum;
		for (var i = 0; i < len; i++) {
			loadPlugin_(names[i]);
		}
		
		function loadPlugin_(name) {
			var plugin = plugins[name];
			if (!plugin && console) {
				console?console.log("找不到插件:" + name):void(0);
				return;
			}
			if (plugin.status === LOADED) {
				pluginNum--;
				if (pluginNum <= 0) {
					callback?callback():void(0);
				}
				return;
			} else if (plugin.status === LOADING) {
				plugins[name].callback = (function(defCallback, appendCallback) {
					return function() {
						defCallback?defCallback():void(0);
						appendCallback?appendCallback():void(0);
					};
				})(plugins[name].callback, callback);
				return;
			}
			
			plugins[name].status = LOADING;
			
			var len = plugin.css.length;
			for (var j = 0; j< len; j++) {
				var cssPath = g_contextPath + plugin.css[j];
				$("head").append('<link href="' + cssPath + '" rel="stylesheet" type="text/css" />');
			}
			
			if (plugin.js.length > 0) {
				load_(plugin.js, 0);
			}
			
			function load_(jss, i) {
				require([jss[i]], function() {
					if (i < jss.length - 1) {
						load_(jss, i + 1);
						return;
					}
					plugins[name].status = LOADED;
					plugins[name].callback?plugins[name].callback():void(0);
					
					pluginNum--;
					if (pluginNum > 0) {
						return;
					}
					callback?callback():void(0);
					
				});
			}
		};
	};
	
	window.doing = function(bool) {
		if (bool === undefined) {
			return $(document).data("doing");
		}
		if (bool === false) {
			setTimeout(function() {
				$(document).data("doing", bool);
			},500);
		} else {
			$(document).data("doing", bool);
		}
		return bool;
	};

	window.clearSessionStorage = function() {
		if (!sessionStorage) {
			return null;
		}
		sessionStorage.clear();
	};
	window.setLocalStorage = function(key, data) {
		if (!localStorage) {
			return;
		}
		localStorage.setItem(key, data);
	};
	window.getLocalStorage = function(key) {
		if (!localStorage) {
			return null;
		}
		return localStorage.getItem(key);
	};


	loadjs(["common"]);
	
	// 其它公共处理####################################################################################

	// 扩展属性
	$.extend($.fn,{
		its: function(attrValue) {
			return $(this).find("[its=" + attrValue + "]");
		}
	});

	// 扩展滚动事件
	$.extend($.fn,{
		scrollLoad: function(callback) {
			if (!callback) {
				load_();
				return $that;
			}
			var eventName = 'lazyWork';
			var $that = $(this);
			var isDoing = false;
			
			$(document).on(eventName, $that.selector, function() {
				var $target = $(this);
				var elHeight = $target.height();
				var elTop = $target.offset().top;
				var wHeight = $(window).height();
				var wScrollTop = $(window).scrollTop();
				if ((wScrollTop >= elTop && wScrollTop < (elTop + elHeight)) || (wScrollTop < elTop && (wScrollTop + wHeight) >= elTop) ) {
					callback($target);
				}
			});
			
			$(window).scroll(load_);
			$(window).scroll();
			
			function load_() {
				if (isDoing) return;

				isDoing = true;
				setTimeout((function(selector) {
					return function() {
						$(selector).each(function() {
							$(this).trigger(eventName);
						});
						isDoing = false;
					};

				})($that.selector));
			}
			return $that;
		}
	});
	
	$.extend($.fn,{
		showMsg: function(msg, type, lock) {
			var $this = $(this);
			if (!msg) {
				$this.trigger('hideMsg');
				setTimeout(function() {
					$this.data('locked', false);
				},1000);
				return true;
			}
			
			if (lock && $this.data('locked')) {
				return false;
			}
			
			if (lock) {
				$this.data('locked', true);
			} else {
				setTimeout(function() {
					$this.data('locked', false);
				},1000);
			}
			
			if ($this.data('hasMsg')) {
				$this.trigger('changeMsg', [msg, type]);
				return true;
			}
			$this.data('hasMsg', true);
			
			var $el = $('.myMsg');
			if ($el.length === 0) {
				$el = $("<div class='myMsg'></div>");
				$("body").prepend($el);
			}
			var $tip = $('<div style="margin-top:5px;"></div>');
			$el.append($tip);
			
			$this.on('changeMsg', function(event, msg, type) {
				$tip.attr('class', type);
				$tip.html(msg);
				if (type !== 'load') {
					$tip.stop(true,true).show().delay(2000).fadeOut(function() {$tip.hide();});
				} else {
					$tip.show();
				}
				return false;
			});
			$this.on('hideMsg', function() {
				$tip.fadeOut();
				return false;
			});
			
			$this.trigger('changeMsg', [msg, type]);
		
			return true;
		},
		doing: function(bool) {
			var $this = $(this);
			var preDoing = $this.data('locked');
			if (bool === undefined) {
				return preDoing;
			}
			if (bool === false) {
				setTimeout(function() {
					$this.removeData("locked");
				},1000);
			} else if (!preDoing) {
				$this.data("locked", bool);
			}
			return preDoing; 
		}
	});

	// (ie兼容plascholder)
	require(["placeholder"], function() {
		// (ie兼容plascholder)
		$("input,textarea").placeholder();
		// (ie兼容autofocus)
		$("[autofocus]").focus().select();
	});
	
	// 日期类扩展
	Date.prototype.format = function(fmt) { //author: meizz   
	  var o = {   
	    "M+" : this.getMonth()+1,                 //月份   
	    "d+" : this.getDate(),                    //日   
	    "h+" : this.getHours(),                   //小时   
	    "m+" : this.getMinutes(),                 //分   
	    "s+" : this.getSeconds(),                 //秒   
	    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
	    "S"  : this.getMilliseconds()             //毫秒   
	  };   
	  if(/(y+)/.test(fmt)) {
	  	fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));  
	  }  
	     
	  for(var k in o) {
	    if(new RegExp("("+ k +")").test(fmt))   {
	  		fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
	    }
	  }
	  return fmt;   
	};
	
	// 订单通知
	(function() {
		
		var $target = $("<div>");
		var intervalIndex = -1;
		
		if (getLocalStorage("isShowNewOrderTip") !== "false") {
			//start_();
		} 
		
		// 查看订单
		$(document).on('click', "#seeNewOrder", function() {
			location.href = g_shopDomain + "/order/list?statuses=0,2";
		});
		
		// 音乐开关切换
		$(document).on('click', "#oss", function() {
			// 将开关状态保存在本地缓存
			setLocalStorage("isPlayNewOrderAudio", getLocalStorage("isPlayNewOrderAudio") !== "false" ? "false" : "true");
			$(document).trigger('newOrderAudioSwitch.change');
		});
		
		$(document).on('newOrderTipSwitch.change', function() {
			$target.doing(false);
			stop_();
			if (getLocalStorage("isShowNewOrderTip") === "false") {
				$target.showMsg();
			} else {
				start_();
			}
		});
		
		$(document).on('newOrderAudioSwitch.change', function() {
			if (getLocalStorage("isPlayNewOrderAudio") === "false") {
				$("#oss").addClass("voloff");
				stop_();
			} else {
				$("#oss").removeClass("voloff");
				if ($("#oss").length > 0 && !playing_()) {
					play_();
				}
			}
		});
		
		function start_() {
			loadStatus_();
			clearInterval(intervalIndex);
			intervalIndex = setInterval(loadStatus_, 30000);
		}
		
		function loadStatus_() {
			if ($target.doing()) {
				clearInterval(intervalIndex);
				return;
			}
			$.get(g_contextPath + "/common/orderTip/json?=r" + Math.random(), function(data) {
				if (data.status != 0) {
					clearInterval(intervalIndex);
					return;
				}
				// data.result -> isNewOrder (boolean)
				if (!data.result && $target.doing()) {
					
					$target.showMsg();
					stop_();
					
				} else if (data.result && !$target.doing()) {
					
					var vol = "voloff";// style class name
					
					// 从本地缓存中获得播放开关状态
					if (getLocalStorage("isPlayNewOrderAudio") !== "false") {
						play_();
						vol = "";
					}
					
					// oss -> orderSoundSwitch
					$target.showMsg("<a id='oss' class='voldef " + vol + "'></a><a id='seeNewOrder' class='newmsg'>有新订单！</a>", 'load', true);
				}
				
			});
		}
		
		function play_() {

			var source = g_resDomain + "/images/new_order";
			$("body").append("<audio id='orderAudio' autoplay loop class='simulatehide'> <source src='" + source + ".mp3'></source> <source src='" + source + ".ogg'></source></audio>");
			require(["media"], function() {
				html5media();
			});
		}
		
		function stop_() {
			$("#orderAudio").remove();
		}
		
		function playing_() {
			return $("#orderAudio").length > 0;
		}
	})();
	
	//公共表单样式
	  $(".fill p").addClass("f_clear");
	  $(".form input[type=text],.form input[type=password],.form textarea").addClass("k");
	  $(".form input[type=radio]").addClass("radio");
	  $(document).on("focus", ".form input[type=text],.form input[type=password],.form textarea", function() {
		  $(this).addClass("hover");
		  $(this).addClass("selected");
	  }).on("blur", ".form input[type=text],.form input[type=password],.form textarea", function() {
		  $(this).removeClass("hover");
		  $(this).removeClass("selected");
	  });
	  $(document).on("focus", ".form select", function() {
		  $(this).addClass("selected");
	  }).on("blur", ".form select", function() {
		  $(this).removeClass("selected");
	  });
	 //
});

